package com.google.project.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.SpecializeService;
import com.google.project.server.entity.Specialize;
import com.google.project.shared.SpecializeDTO;

@SuppressWarnings("serial")
public class SpecializeServiceImpl extends RemoteServiceServlet implements SpecializeService {
	
	/***
	 * add new Specialize
	 */
	@Override
	public SpecializeDTO addSpecialize(SpecializeDTO specializeDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Specialize spec=null;
		try {
			spec = new Specialize(specializeDTO);
			pm.makePersistent(spec);
		}catch(Exception e){
			e.printStackTrace();
		
		} finally {
			pm.close();
		}
		return null;
	}
	
	/***
	 * get all List Specialize
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<SpecializeDTO> getSpecList() {
		List<SpecializeDTO> specList = new ArrayList<SpecializeDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Specialize.class);
		try {
			List<Specialize> list = (List<Specialize>) q.execute();
			for (Specialize specialize : list) {
				specList.add(specialize.toDTO());
			}
		} catch (Exception e) {
			// logger.warning(e.getMessage());
		} finally {
			pm.close();
		}
		return specList;
	}
	
	/***
	 * deleteSpecialize
	 */
	@Override
	public void deleteSpecialize(String specializeId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Specialize specialize = pm.getObjectById(Specialize.class, specializeId);
			if (specialize != null) {
				pm.deletePersistent(specialize);
			}
		} finally {
			pm.close();
		}
		
	}
	/***
	 * 	get specialize by ID
	 */
	@Override
	public SpecializeDTO getSpecializeById(String specializeId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Specialize specializeInfo;
	    try {
	    	specializeInfo = pm.getObjectById(Specialize.class, specializeId);
	
	    } finally {
	      pm.close();
	    }

	    return specializeInfo.toDTO();
	}

	@Override
	public void updateSpecialize(SpecializeDTO specializeDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Specialize specialize = null;
		try {
			specialize = pm
					.getObjectById(Specialize.class, specializeDTO.getId());
			specialize.updateFromDTO(specializeDTO);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		
	}

	@Override
	public void deleteSpecializeList(List<SpecializeDTO> list) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			for (SpecializeDTO specializeDTO : list) {
				Specialize specialize = pm.getObjectById(Specialize.class, specializeDTO.getId());
				if (specialize != null) {
					pm.deletePersistent(specialize);
				}
			}
		
		} finally {
			pm.close();
		}
	}	
	
}
